<?php
namespace Home\Controller;
use Think\Cache\Driver\Redis;
class GoodController extends CommonController
{
    public function redistest(){
        header("content-type:text/html;charset=utf-8");
        $redis = new \redis();
        $redis->connect('119.23.24.184', 6379);
        $redis->auth("123456");
        $mywatchkey = $redis->get("mywatchkey");
        $rob_total = 5;   //抢购数量
        if($mywatchkey<$rob_total){
            $redis->watch("mywatchkey");
            $redis->multi();
            //设置延迟，方便测试效果。
//            sleep(2);
            //插入抢购数据
            $redis->hSet("mywatchlist","user_id_".mt_rand(1, 9999),time());
            $redis->set("mywatchkey",$mywatchkey+1);
            $rob_result = $redis->exec();
            if($rob_result){
                $mywatchlist = $redis->hGetAll("mywatchlist");
                echo "抢购成功！<br/>";
                echo "剩余数量：".($rob_total-$mywatchkey-1)."<br/>";
                echo "用户列表：<pre>";
                var_dump($mywatchlist);
            }else{
                echo "手气不好，再抢购！";exit;
            }
        }
    }

    public function agentgoods()
    {
        //是否为代理
        $is_agent = M('agent')->where( array('agent_id'=>session('user_id')) )->getField('is_agent');

        //过滤条件
        $sort = I('get.sort');
        $price = I('get.price');
        $cate_id = to_int(I('get.id'));


        $sale = I('get.sale');
        //新品优先
        $new = I('get.new');
        if ($new == 1) {$order_by = 'id DESC';}
        //价格
        if ($price == 'reduce') {
            $order_by = 'price DESC';
        } elseif ($price == 'plus') {
            $order_by = 'price ASC';
        }
        //销量
        if ($sale == 'reduce') {
            $order_by = 'sale_num DESC';
        } elseif($sale == 'plus') {
            $order_by = 'sale_num ASC';
        }
        //综合排序
        $ranking = I('get.ranking');
        if ($ranking == 1) {
            $order_by = 'sale_num DESC,price DESC,id DESC';//销量高，价格便宜，发布较新
        }

        //品牌
        $brand_id = I('get.brand_id');

        if ($is_agent == 1 && empty($brand_id)) {
            $brandid = M('agent_brand')->where(array('agent_id' => session('user_id')))->select();
            foreach ( $brandid as $val) {
                $brandida[] = $val['brand_id'];
            }
            $n_agent_brands = M('brand')->where('agent_brand = 0')->field("id")->select();
            foreach($n_agent_brands as $n_b){
                $brandida[] = $n_b["id"];
            }
            $map['brand_id'] = array('in',$brandida);
        } else {
            if(! empty($brand_id)) $map = array('brand_id'=>$brand_id);
        }


        if (!empty($cate_id) && isset($cate_id)) {
            $map['cate'] = $cate_id;
        }
        //搜索
        $map['shelves'] = 1;
        $good = M('good')->where($map)->limit(6)->order($order_by)->select();
        $goods = get_unit_amt($good);
        $mName = trim(I('get.mName'));
        if (!empty($mName)) {
            $map['g_name'] = array('like',"%$mName%");
            $good = M('good')->where($map)->order($order_by)->select();
            $goods = get_unit_amt($good);
            $keywords = trim(I('mName'));
            if ($keywords != '') {
                foreach($goods as $key=>$value){
                    if(strstr($value['g_name'],$keywords)!==false){
                        $goodss[] = $value;
                    }
                }
            }
            $this->assign('agentgoods',$goodss);
            $this->assign('agentgoods2',$goodss);
        } else {
            $this->assign('agentgoods',$goods);
            $this->assign('agentgoods2',$goods);
        }
        //获取代理商代理的所有的品牌
        if ($is_agent == 1) {
            $brands = M('agent_brand')->alias('a')
                ->field('a.brand_id,b.b_name')
                ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id')
                ->where(array('a.agent_id'=>session('user_id')))
                ->select();
        } else {
            $brands = M('brand')->field('id as brand_id,b_name')->select();
        }

        //分类名称
        $c_name = M('category')->where( array('id'=>I('get.id')) )->getField('c_name');
        $this->assign('c_name', $c_name);
        $this->assign('model', I('get.model'));
        $this->assign('sort', $sort);
        $this->assign('id',to_int(I('get.id')));
        $this->assign('brands',$brands);
        $this->assign('price', $price);
        $this->assign('brand_id', $brand_id);
        $this->assign('ranking', $ranking);
        $this->assign('sale', $sale);
        $this->assign('new', I('get.new'));
        $this->assign('params' ,get_url_params());
        $this->assign('is_agent', $is_agent);
        $this->site_title = "商品列表";
        $this->display();
    }

    //分类页面
    public function cate()
    {
        $category = M('category')->where("status = 1 AND pid = 0")->order('sort ASC')->select();
        foreach($category as $key => $c_val){
            $category[$key]['sub_cat'] = M('category')
                ->where("pid = %d AND status = 1",array($c_val['id']))
                ->order("'sort ASC'")->select();
        }

        $this->assign('categories', $category);
        $this->site_title="商品分类";
        $this->display();
    }

    public function moreagent()
    {
        $params = I("post.params");
        $where = pre_params($params);
        if(!empty($where['id'])){
            $map['cate'] = $where['id'];
        }

        if(!empty($where['mName'])){
            $map['g_name'] = array("like", "%{$where['mName']}%");
        }
        if(!empty($where['brand_id'])){
            $map['brand_id'] = $where['brand_id'];
        } else {
            $brandid = M('agent_brand')->where(array('agent_id'=>session('user_id')))->select();
            foreach ( $brandid as $key=>$val) {
                $brandida[$key]=$val['brand_id'];
            }
            $n_agent_brands = M('brand')->where('agent_brand = 0')->field("id")->select();
            foreach($n_agent_brands as $n_b){
                $brandida[] = $n_b["id"];
            }
            $map['brand_id'] = array('in',$brandida);
        }
        if(!empty($where['price'])) {
            $order_by = ($where['price'] == 'reduce') ? 'price DESC' : 'price ASC';
        }

        //销量
        if(!empty($where['sale'])) {
            $order_by = ($where['sale'] == 'reduce') ? 'sale_num DESC' : 'sale_num ASC';
        }

        if ($where['ranking'] == 1) {
            $order_by = 'sale_num DESC,price DESC,id DESC';
        }
        if ($where['new'] == 1) {
            $order_by = 'id DESC';
        }
        $pageSize = 6;
        $page = $_POST['page'] ? to_int(I("post.page")) : 1;
        $pageB = ($page - 1) * $pageSize;
        //$map['type'] = 1;
        $map['shelves'] = 1;
        $good = M('good')->where($map)->limit($pageB ,$pageSize)->order($order_by)->select();
        //echo M('good')->getLastSql();
        $goods = get_unit_amt($good);
        if(empty($goods)){
            echo 1;
        } else{
            $this->assign('agentgoods',$goods);
            $this->assign('agentgoods2',$goods);
            $model = I('post.model');
            if ($model == 2) {
                $this->display('moreagent_b');
            } else {
                $this->display('moreagent_a');
            }
        }
    }
    //商家商品列表
    public function businessgoods()
    {
//        读取菜单名称
        $category = get_category();
//        搜索
        if (isset($_REQUEST['mName']) || isset($_REQUEST['id'])){
            $cate_id = I('get.id');
            $mName = trim(I('get.mName'));
            if($cate_id != ''){
                $where['cate'] = $cate_id;
                $cate = M('category')->where(array('id'=>$cate_id))->find();
                $this->site_title=$cate['c_name'];
            }
            if($mName != ''){
                $cWhere['g_name'] = array("like", "%$mName%");
                $cWhere['price'] = array("eq", $mName);
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }else{
            $this->site_title = "商品列表";
        }
//        读取商品信息
        $where['type'] = 2;
        $where['shelves'] = 1;
        $res = M('good')->where($where)->order('id DESC')->limit(0,10)
            ->select();
//        $this->site_title = "商品列表";
        $this->assign('params' ,get_url_params());
        $this->assign('categories', $category);
        $this->assign('businessgoods', $res);
        $this->display();
    }

    public function morebusiness()
    {
        $params = I("post.params");
        $param_where = pre_params($params);
        if(!empty($param_where['id'])){
            $where['cate'] = $param_where['id'];
            unset($param_where['id']);
        }
        $where['type'] = 2;
        $where['shelves'] = 1;
        $pageSize = 10;
        $page = $_POST['page'] ? to_int(I("post.page")) : 1;
        $pageB = ($page - 1) * $pageSize;
        if(!empty($param_where['mName'])){
            $mName = $param_where['mName'];
            unset($param_where['mName']);
            if ($mName != '') {
                $cWhere['g_name'] = array("like", "%$mName%");
                $cWhere['price'] = array("eq", $mName);
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }
        $res =M('good')->where($where)->order('id DESC')->limit($pageB, $pageSize)
            ->select();
        if(empty($res)){
            echo 1;
        }else{
            $this->assign('businessgoods',$res);
            $this->display();
        }
    }

    //商品详情
    public function goodsdetail()
    {
        //是否为代理
        $is_agent = M('agent')->where( array('agent_id'=>session('user_id')) )->getField('is_agent');
        $goodid = to_int(I('get.id'));
        $good = M('good')->where(array('id' => $goodid))->find();

        $brand_id = $good['brand_id'];
        $res = M('agent_brand')->where(array('agent_id'=>session('user_id'),'brand_id'=>$brand_id))->find();

        //查询商品的规格和规格值
        $goodSpec = M('goodSpec')->alias('a')->field('a.good_id,b.s_name, a.spec_val')
            ->join('LEFT JOIN __SPEC__ b ON a.spec_id=b.id')
            ->where( array('a.good_id'=>$goodid) )->select();
        $spec = M('spec')->order('id ASC')->select();
        foreach ($goodSpec as $k=>$v) {
            $goodSpec[$k]['spec_val'] = explode(',', $goodSpec[$k]['spec_val']);
        }
        $c_name = M('category')->where(array('id'=>$good['cate']))->find();
        $b_name = M('brand')->where(array('id'=>$good['brand_id']))->find();
        $goodpic = M('good_pic')->where(array('good_id'=>$goodid))->select();
        //如果商品是代理商品的话
        if($b_name["agent_brand"] == 1){
            $rankprice= M('good_rank_price')->where(array('good_id'=>$goodid,'rank_id'=>$res['rank_id']))->find();
            $good['unit_amt']=$rankprice['unit_amt'];
            $good['batch_amt']=$rankprice['batch_amt'];
        }
        $status = "none";
        $self_address = M("agent_address")->where("state = 0 AND agent_id = %d",session("user_id"))->find();
        if($self_address){
            $status = "has";
        }


        $this->assign("self_address" ,$status);
        $this->assign('goodpic',$goodpic);
        $this->assign('b_name',$b_name['b_name']);
        $this->assign('agent_brand',$b_name["agent_brand"]);
        $this->assign('c_name',$c_name['c_name']);
        $this->assign('id',$goodid);
        $this->site_title = "详情列表";
        $this->assign('goodsdetail',$good);
        $this->assign('spec', $spec);
        $this->assign('goodSpec',$goodSpec);
        $this->assign('is_agent', $is_agent);
        $this->display();
    }

//添加购物车
    function addcart()
    {
        $b_id = I('post.brand_id');
        $good_id = I('post.good_id');
        $num = I('post.num');
//        状态码0是非代理1件2箱
        $status = I('post.status');
//        $attr = I('post.attr');
        $agent_id = session('user_id');
        $redis = new \Redis();
        $redis->connect('119.23.24.184', 6379);
        $redis->auth("123456");
//        先在redis里面查找有没有购物车数据
        $jsonStr = $redis->get($agent_id . '_shoplist');
        if (!$jsonStr) {
            $cart_info[0]['good_id'] = $good_id;
            $cart_info[0]['good_num'] = $num;
            $cart_info[0]['status'] = $status;
            $redis->set($agent_id . "_shoplist", json_encode($cart_info));
            $this->ajaxReturn(1);
        } else {
            $reh = 0;
            $jsonStr_true = json_decode($jsonStr,true);
            foreach ($jsonStr_true as $key => $val) {
                    if ($good_id == $val['good_id']) {
                        if ($status == $val['status']) {
                            $val['good_num'] = $val['good_num'] + $num;
                            $reh = 1;
                    }
                }
                $jsonStr_true[$key] = $val;
            }
            if ($reh == 0) {
//                返回数组键名倒序取最大
                $ar_keys = array_keys($jsonStr_true);
                rsort($ar_keys);
                $max_array_keyid = $ar_keys[0] + 1;
                $cart_info['good_id'] = $good_id;
                $cart_info['good_num'] = $num;
                $cart_info['status'] = $status;
                $jsonStr_true[$max_array_keyid] = $cart_info;
            }
            $redis->set($agent_id."_shoplist",json_encode($jsonStr_true));
            $this->ajaxReturn(1);
        }
    }

    public function shopcart()
    {
        $agent_id = session('user_id');
        $redis = new \Redis();
        $redis->connect('119.23.24.184', 6379);
        $redis->auth("123456");
        $res = $redis->get($agent_id . "_shoplist");
        $shopcart = json_decode($res, true);
//      删除
        if (IS_AJAX) {
            $cart_id = I('post.cookie_id');
            unset($shopcart[$cart_id]);
            $redis->set($agent_id."_shoplist",json_encode($shopcart));
            $this->ajaxReturn(1);
        } else {
//          展示
//            $res = M('shop_cart')->where(array('agent_id'=> session('user_id')))->order('cart_id DESC')->select();
//          查询商品库里的商品核对是否有新更新
            foreach ($shopcart as $key => $val) {
                $good = M('good')->where(array('id' => $val['good_id']))->find();
//          判断商品是否下架
                $val['good_id'] = $good['id'];
                $val['good_pic'] = $good['img'];
                $val['good_name'] = $good['g_name'];
                $val['cart_id'] = $key;
                if ($good['shelves'] == -1) {
                    $val['expired'] = 1;
                } else {
//          不下架跟新当时的价格
                    $val['expired'] = -1;
                    //        判断是否是普通用户
                    $agenttype = M('agent')->where(array('agent_id' => session("user_id")))->getField('is_agent');
                    if ($agenttype == 2) {
                        $val['price'] = $good['price'];
                    } else {
                        //            防止有商家没填拿货价，就用商品售价
                        $new_rank_id = M('agentBrand')->where(array('brand_id' => $good['brand_id'], 'agent_id' => session('user_id')))->getField('rank_id');
                        $res = M('good_rank_price')->where(array('good_id' => $good['id'], 'rank_id' => $new_rank_id))->find();
                        if (!$res) {
                            $val['price'] = $good['price'];
                        } else {
                            if ($val['status'] == 1) {
                                $val['price'] = $res['unit_amt'];
                            } else {
                                $val['price'] = $res['batch_amt'];
                            }
                        }
                    }
                    $shopcart[$key] = $val;
                }
            }
//
                $this->assign('res', $shopcart);
                $status = "none";

                $self_address = M("agent_address")->where("state = 0 AND agent_id = %d", session("user_id"))->find();
                if ($self_address) {
                    $status = "has";
                }
                $this->assign("self_address", $status);

                $this->display();
            }
        }


    // ajax 拉取子类
    public function ajax_cate_list()
    {
        $where = ' status = 1 ';
        if(isset($_POST['pid']) && $_POST['pid'] != ''){
            (I('pid') !== '') && $where = "$where AND pid = ".I('pid');
        }else{
            $pid = M("category")->where("pid = 0 AND status = 1")->order("sort ASC")->field("id")->find();
            $where = "$where AND pid = ".$pid['id'];
        }
        $cateList = M('category')->where($where)->order("sort ASC")->select();
        $this->assign('cateList',$cateList);
        $this->display();
    }


        public function popp()
        {
            $fset =array(
                'WUST'=>'WUHAN SI',
                 'birth'=>1031,
                'marray'=>array(
                 'apple'=>'苹果',
                 'orange'=>'org',
                ),
            );
            $redis = new \Redis();
            $redis->connect('119.23.24.184', 6379);
                    $redis->auth("123456");
            $redis->hMset('tuntun',$fset);
            $str = $redis->hMGet('tuntun',array('marray'));
            $redis->hgetall('tuntun');
            var_dump($str);

        }
//
//        public function addToCart($gid, $cartNum=1)
//        {
//
//            session_start();
//            if ($gid <= 0) {
//
//                throw new Exception("请输入商品ID");
//
//            }
//
//            //根据商品ID查询商品数据
//            $goodData = $this->goodsData($gid);
//
//            $key = 'cart:'.session_id().':'.$gid;//id 说明：1、不仅仅要区分商品  2、 用户
//
//            // $data = $this->redis->hget($key, 'id');
//            $data = $this->redis->exists($key);
//
//
//            //判断购物车中是否有无商品，然后根据情况加入购物车
//            if (!$data) {
//
//                //购物车之前没有对应的商品的
//
//                //购物车的商品数量
//                $goodData['num'] = $cartNum;
//
//                //将商品数据存放到redis中hash
//                $this->redis->hmset($key, $goodData);
//
//
//            $key1 = 'cart:ids:set:'.session_id();
//
//            //将商品ID存放集合中,是为了更好将用户的购物车的商品给遍历出来
//            $this->redis->sadd($key1, $gid);
//
//        } else {
//
//                //购物车有对应的商品，只需要添加对应商品的数量
//                $originNum = $this->redis->hget($key, 'num');
//
//                //原来的数量加上用户新加入的数量
//                $newNum = $originNum + $cartNum;
//
//                $this-&gt;redis-&gt;hset($key, 'num', $newNum);
//
//
//        }
//
//        }
//
//    }

}